package cn.lblbc.cootext

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class SearchHistoryAdapter(
    private var historyList: MutableList<String>,
    private val onItemClickListener: (String) -> Unit,
    private val onDeleteClickListener: (String, Int) -> Unit
) : RecyclerView.Adapter<SearchHistoryAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val historyTextView: TextView = view.findViewById(R.id.historyTextView)
        val deleteButton: ImageButton = view.findViewById(R.id.deleteHistoryButton)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_search_history, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val historyItem = historyList[position]
        holder.historyTextView.text = historyItem
        
        holder.historyTextView.setOnClickListener {
            onItemClickListener(historyItem)
        }
        
        holder.deleteButton.setOnClickListener {
            onDeleteClickListener(historyItem, position)
        }
    }

    override fun getItemCount() = historyList.size

    fun updateData(newList: List<String>) {
        historyList.clear()
        historyList.addAll(newList)
        notifyDataSetChanged()
    }
}